import { createStore } from 'vuex'
import { M_CONSTANT } from './mutation-types'
import axios from 'axios'
import home from './modules/home'

export default createStore({
  state() {
    return {
      counter: 0,
      name: 'slim',
      age: '18',
      books: [
        { name: '深入Vuejs', price: 200, count: 3 },
        { name: '深入Webpack', price: 240, count: 5 },
        { name: '深入React', price: 130, count: 1 },
        { name: '深入Node', price: 220, count: 2 }
      ],
      discount: 0.6,
      banners: []
    }
  },
  getters: {
    doubleCounter(state){
      return state.counter * 2;
    },
    totalPrice(state, getters) {
      let totalPrice = 0
      for (const book of state.books) {
        totalPrice += book.count * book.price
      }
      return totalPrice * getters.currentDiscount
    },
    totalPriceCountGreaterN(state, getters) {
      return function(n) {
        let totalPrice = 0
        for (const book of state.books) {
          if (book.count > n) {
            totalPrice += book.count * book.price
          }
        }
        return totalPrice * getters.currentDiscount
      }
    },
    currentDiscount(state) {
      return state.discount * 0.9
    },
    nameInfo(state) {
      return `nameInfo ${state.name}`
    },
    ageInfo(state) {
      return `ageInfo ${state.age}`
    }
  },
  mutations: {
    increase(state) {
      state.counter++
    },
    decrease(state) {
      state.counter--
    },
    increaseN(state, payload) {
      state.counter += payload.n
    },
    [M_CONSTANT](state, payload) {
      console.log('payload: ', payload)
    },
    addBannerData(state, payload) {
      state.banners = payload
    }
  },
  actions: {
    increaseAction(context, payload) {
      console.log(payload)
      setTimeout(() => {
        context.commit('increase')
      }, 1000)
    },
    decreaseAction({ commit, dispatch, state, rootState, getters, rootGetters }, payload) {
      console.log(payload)
      setTimeout(() => {
        commit('decrease')
      }, 1000)
    },
    getRemoteData(context) {
      return new Promise((resolve, reject) => {
        axios
          .get('http://123.207.32.32:8000/home/multidata')
          .then((res) => {
            context.commit('addBannerData', res.data.data.banner.list)
            resolve({ name: 'slim', age: 18 })
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  },
  modules: { home }
})
